<!--
 * @Author: your name
 * @Date: 2020-03-26 09:41:08
 * @LastEditTime: 2020-03-26 09:41:10
 * @LastEditors: Please set LastEditors
 * @Description: 云美贝
 -->

<template>
  <div>
    <van-form class="yunmeibei-form">
      <van-field
        v-model="ruleForm.username"
        type="tel"
        maxlength="11"
        label="账号"
        placeholder="请填写账号"
        clearable
      />
      <van-field
        v-model="ruleForm.password"
        type="password"
        label="密码"
        placeholder="请填写密码"
        clearable
      />
      <van-field v-model="IntervalTime" type="tel" label="抢单间隔(s)" placeholder="请填写抢单间隔" clearable />
      <van-field name="radio" label="任务类型">
        <template #input>
          <van-radio-group v-model="type" direction="horizontal">
            <van-radio
              v-for="(option, index) in typeOptions"
              :key="index"
              :name="option.type"
              checked-color="#e4393c"
            >{{ option.label }}</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-cell-group>
        <van-cell
          class="van-cell__tip"
          v-for="(content, index) in returnContent"
          :key="index"
          :title="content"
        />
      </van-cell-group>
    </van-form>
    <div class="popup-open__btn">
      <van-button type="warning">做单</van-button>
      <van-button type="danger" @click="onStart">{{ startFlag ? '停止接单' : '开始接单' }}</van-button>
    </div>

    <!-- 选择账号 -->
    <van-dialog v-model="show" title="选择账号" :showConfirmButton="false" :showCancelButton="false">
      <van-cell v-for="(bind, index) in bindInfo" :key="index" center :title="bind.accountname">
        <template #right-icon>
          <van-switch
            v-model="bind.status"
            active-color="#e4393c"
            size="24"
            @change="onChange(bind)"
          />
        </template>
      </van-cell>
    </van-dialog>
  </div>
</template>

<script>
import { alertMsg, saveInfo, audio } from "@/utils/index";
import dayjs from "dayjs";
export default {
  name: "Yunmeibei",
  props: {
    index: {
      type: String,
      default: ""
    },
    item: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      ruleForm: {
        username: "",
        password: "",
        isAdmin: 0
      },
      IntervalTime: 30,
      type: "2",
      typeOptions: [
        { label: "货返", type: "1" },
        { label: "立返", type: "2" }
      ],
      startFlag: false,
      returnContent: [],
      token: "",
      taskId: "",
      timer: null,
      // 已接单标记
      isAcceptSuc: false,
      activeIndex: "",
      show: false,
      bindInfo: [],
      cookie: ""
    };
  },
  watch: {
    // 监听接单状态
    startFlag() {
      if (this.item.index === 16 && this.index !== "") {
        this.$emit("changeOpened", {
          index: this.index,
          status: this.isAcceptSuc
            ? "已接单"
            : this.startFlag
            ? "已启动"
            : "待启动",
          startFlag: this.startFlag,
          content: this.returnContent
        });
      }
    },
    returnContent() {
      if (this.returnContent.length >= 10) {
        this.returnContent = this.returnContent.filter((item, i) => i < 5);
      }
    },
    // 监听当前索引
    index() {
      if (this.item.index === 16 && this.index !== "") {
        this.activeIndex = this.index;
        // 获取保存账号信息
        this.ruleForm.username = this.item.user;
        this.ruleForm.password = this.item.pass;
        this.type = this.item.type || "2";

        // 如为 已接单 => 改变状态
        if (this.item.opened === "已接单") {
          this.$emit("changeOpened", {
            index: this.index,
            status: "待启动",
            startFlag: this.startFlag,
            content: this.returnContent
          });
        }
      }
    }
  },
  created() {
    if (this.item.index === 16 && this.index !== "") {
      this.activeIndex = this.index;
      // 获取保存账号信息
      this.ruleForm.username = this.item.user;
      this.ruleForm.password = this.item.pass;
      this.type = this.item.type || "2";
    }
  },
  methods: {
    // 开始接单
    onStart() {
      const _this = this;
      clearInterval(this.timer);
      if (!this.startFlag) {
        if (!/^1[3456789]\d{9}$/.test(this.ruleForm.username)) {
          this.$toast("手机号码输入有误");
          return false;
        }
        if (this.ruleForm.password === "") {
          this.$toast("密码输入有误");
          return false;
        }
        if (this.IntervalTime === "") {
          this.$toast("抢单间隔输入有误");
          return false;
        }
        // 登录
        this.returnContent = [];
        this.startFlag = true;
        this.returnContent.unshift(alertMsg("正在登录"));
        this.$ajax({
          url: "http://m.yunmeibei.cn/app.ashx?action=login_submit",
          type: "post",
          ajaxData: {
            values: _this.ruleForm
          },
          returnAll: true,
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            "X-Requested-With": "XMLHttpRequest"
          },
          method: function(res) {
            _this.returnContent.unshift(
              alertMsg(res.body.msgbox || "登录异常，正在重新登录")
            );
            if (res) {
              _this.cookie = res.headers["Set-Cookie"];
              if (res.body.msg === 1) {
                // 登录成功  => 保存账号信息
                saveInfo({
                  user: _this.ruleForm.username,
                  pass: _this.ruleForm.password,
                  type: _this.type,
                  index: _this.index
                });
                // 获取账户信息
                _this.onGetModelByChannelId(_this);
              } else {
                _this.startFlag = false;
                _this.timer = setInterval(() => {
                  _this.onStart();
                }, 2000);
              }
            } else {
              _this.startFlag = false;
              _this.timer = setInterval(() => {
                _this.onStart();
              }, 2000);
            }
          }
        });
      } else {
        this.returnContent.unshift(alertMsg("接单取消"));
        clearInterval(_this.timer);
        this.startFlag = false;
        this.isAcceptSuc = false;
        this.$toast({ message: "已停止接单" });
      }
    },
    // 获取账户信息
    onGetModelByChannelId(_this) {
      _this.bindInfo = [];
      _this.$ajax({
        url: "http://m.yunmeibei.cn/app.ashx?action=GetModelByChannelId",
        type: "post",
        headers: {
          "X-Requested-With": "XMLHttpRequest",
          Cookie: _this.cookie
        },
        ajaxData: {
          values: {
            channelId: 6,
            id: 0,
            strValue: ""
          }
        },
        method: function(res) {
          if (res.result == 1) {
            res.data.forEach(item => {
              if (item.is_enable == 1) {
                _this.bindInfo.push(item);
              }
            });
            // 开始接单
            if (_this.bindInfo.length === 1) {
              _this.onChange(_this.bindInfo[0]);
            } else {
              _this.show = true;
            }
          } else {
            // 获取账户信息
            _this.onGetModelByChannelId(_this);
          }
        }
      });
    },
    // 选择接单账号
    onChange(data) {
      const _this = this;
      _this.show = false;
      _this.returnContent.unshift(
        alertMsg("接单号: " + data.accountname + "即将开始接单，请等待...")
      );
      _this.onGetList(data);
    },
    // 云美贝任务列表
    onGetList(data) {
      const _this = this;
      clearInterval(_this.timer);
      this.$ajax({
        url: "http://m.yunmeibei.cn/app.ashx?action=GetListByNoTask",
        type: "get",
        ajaxData: {
          values: {
            currPage: 1,
            pageSize: 10,
            type: _this.type,
            taskType: 1,
            accountId: data.id,
            sort: 1,
            _: dayjs().millisecond()
          }
        },
        headers: {
          "X-Requested-With": "XMLHttpRequest",
          Cookie: _this.cookie
        },
        method: function(res) {
          if (res.rowCount === -1) {
            _this.returnContent.unshift(alertMsg("暂无合适任务,努力接单中..."));
            _this.timer = setInterval(() => {
              if (_this.startFlag) {
                _this.onGetList(data);
              }
            }, _this.IntervalTime * 1000);
          } else {
            _this.taskId = res.dataList.length ? res.dataList[0].id : "";
            _this.token = res.token;
            if (_this.taskId) {
              // 若存在 接单
              _this.returnContent.unshift(alertMsg("努力为您接单中..."));
              _this.onGrabSheet(data, _this);
            } else {
              _this.returnContent.unshift(alertMsg("暂无合适任务,继续获取..."));
              _this.timer = setInterval(() => {
                if (_this.startFlag) {
                  _this.onGetList(data);
                }
              }, _this.IntervalTime * 1000);
            }
          }
        }
      });
    },
    // 接单
    onGrabSheet(data, _this) {
      _this.$ajax({
        url: "http://m.yunmeibei.cn/app.ashx?action=updateOrderStatus",
        type: "post",
        ajaxData: {
          values: {
            channelId: 3,
            id: _this.taskId,
            status: 1,
            strValue: "," + data.id + ",2",
            audit: 0,
            token: _this.token
          }
        },
        headers: {
          "X-Requested-With": "XMLHttpRequest",
          Cookie: _this.cookie
        },
        method: function(res) {
          _this.returnContent.unshift(alertMsg(res.Message));
          if (res.IsSuccess === 0) {
            if (res.Message == "正在做任务中") {
              _this.returnContent.unshift(
                alertMsg("您有未完成的订单，请先完成后再抢单...")
              );
              _this.startFlag = false;
            } else {
              _this.timer = setInterval(() => {
                if (_this.startFlag) {
                  _this.onGetList(data);
                }
              }, _this.IntervalTime * 1000);
            }
          } else {
            _this.returnContent.unshift(alertMsg("接单成功，请前往做单..."));
            audio();
            _this.isAcceptSuc = true;
            _this.startFlag = false;
            _this.$emit("changeOpened", {
              index: _this.activeIndex,
              status: "已接单",
              startFlag: false,
              content: ["接单成功，请前往做单..."]
            });
          }
        }
      });
    }
  }
};
</script>
